const config = require('./config');

App({
  onLaunch: function (options) {
    var _this = this;
    // 获取用户信息
    this.getWxInfo((err, wxInfo) => {
      console.log(wxInfo);
    });
    // 登录
    this.getUserInfo((err, userInfo) => {
      // var logData = {
      //   userid: userInfo.id,
      //   path: options.path,
      //   query: JSON.stringify(options.query),
      //   scene: options.scene
      // };

      //获取用户设备信息
      /*wx.getSystemInfo({
        success: function (res) {
          logData.brand = res.brand;
          logData.model = res.model;
          logData.version = res.version;
          logData.system = res.system;
        },
        complete: function () {
          _this.uploadUserlog(logData);
        }
      })*/
    });
  },
  globalData: {
    userInfo: null,
    wxInfo: null,
  },
  getUserInfo: function (callback) {
    var self = this

    if (self.globalData.userInfo) {
      callback(null, self.globalData.userInfo);
    } else {
      self.userlogin();
      var time = setInterval(function () {
        if (self.globalData.userInfo){
          clearInterval(time);
          callback(null, self.globalData.userInfo);      
          
          return false;
        }
      }, 150);
    }
  },
  userlogin: function(){
    var self = this;
    if (self.globalData.islogin) {
      return false;
    }
    self.globalData.islogin = true;

    var wxinfo = wx.getStorageSync('userInfo');
    if (wxinfo && wxinfo.unionid){
      self.globalData.userInfo = wxinfo;
      return false;
    }
    
    wx.login({
      success: res => {
        wx.request({
          url: config.loginUrl,
          header: {
            token: config.token,
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: { code: res.code, dist: "test" },
          method: "POST",
          success: function (result) {
            self.globalData.islogin = true;
            console.log(result);
            if (result && result.data && result.data.status == 0) {
              self.globalData.userInfo = { openId: result.data.openId, 
                                          unionid: result.data.unionid, 
                                          session_key: result.data.session_key };

              wx.request({
                url: config.requerLogininfo,
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                data: { wxOpenId: result.data.openId, pic: "", uniondid: result.data.unionid },
                method: "POST",
                success: function () { }
              });
              wx.setStorageSync("userInfo", self.globalData.userInfo);
            }
          },
          fail: function (res) {
            console.log('拉取用户openid失败，将无法正常使用开放接口等服务', res)
          }
        })
      }, fail: function (err) {
        console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务', err)
      }
    });
  },
  getWxInfo: function (callback) {
    var self = this;
    if (self.globalData.wxInfo) {      
      callback(null, self.globalData.wxInfo)
    } else {      
      wx.getSetting({
        success: res => {          
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              success: res => {
                self.globalData.wxInfo = res.userInfo
                callback(null, res.userInfo)

                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
              },
              fail: res => {
                console.log('拉取用户getUserInfo，将无法正常使用开放接口等服务', res)
                callback(err);
              }
            })
          }else{
            callback('没有授权');
          }
        },
        fail: err => {
          console.log('wx.getSetting 接口调用失败，将无法正常使用开放接口等服务', err)
          callback(err);
        }
      })
    }
  },
  uploadUserlog: function (data) {
    wx.request({
      url: config.pvlogUrl,
      header: {
        token: config.token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      data: data,
      success: function () {

      }
    });
  },
  saveFormid: function (formid) {
    var self = this;
    wx.request({
      url: config.savetempFormidUrl,
      header: {
        token: config.token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: { formid: formid, userid: self.globalData.userInfo.id },
      method: "POST",
      success: function (res) {
        // console.log(res);
      }
    })
  }
})